package com.yh.hljapp.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.jjobes.slidedatetimepicker.SlideDateTimeListener;
import com.github.jjobes.slidedatetimepicker.SlideDateTimePicker;
import com.github.jjobes.slidedatetimepicker.TimeFragment;
import com.google.gson.Gson;
import com.yh.hljapp.AppConfig;
import com.yh.hljapp.AppContext;
import com.yh.hljapp.R;
import com.yh.hljapp.api.ErrorHandler;
import com.yh.hljapp.api.RetrofitSingleton;
import com.yh.hljapp.base.BaseFragment;
import com.yh.hljapp.common.PLog;
import com.yh.hljapp.common.StringUtils;
import com.yh.hljapp.common.Time;
import com.yh.hljapp.common.UIHelper;
import com.yh.hljapp.gddb.gbmanager.AddSale_Manager;
import com.yh.hljapp.gddb.gdbean.Add_Sync_Bean;
import com.yh.hljapp.gddb.gdbean.Qcode;
import com.yh.hljapp.modules.bean.AddQcode_Bean;
import com.yh.hljapp.modules.bean.CM;
import com.yh.hljapp.modules.bean.CustPhone;
import com.yh.hljapp.modules.bean.Result;
import com.yh.hljapp.modules.bean.SimpleBackPage;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Date;

import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * =========================
 * 版权所有，违法必究
 * 作者：zhanghang
 * <p>
 * 工程：hlj
 * <p>
 * 文件名：Code_Fragment
 * <p>
 * 创建时间：2017.09.14.11:39
 */

public class Code_Fragment extends BaseFragment {

    @InjectView(R.id.tv_weight)
    TextView tvWeight;
    @InjectView(R.id.btn_ok)
    Button btnOk;
    @InjectView(R.id.et_weight)
    TextView etWeight;
    @InjectView(R.id.expView_container)
    LinearLayout expView_container;
    @InjectView(R.id.tv_gh_unit)
    TextView tvGhUnit;
    @InjectView(R.id.ll_gh_unit)
    LinearLayout llGhUnit;
    @InjectView(R.id.tv_cp_name)
    TextView tvCpName;
    @InjectView(R.id.ll_cp_name)
    LinearLayout llCpName;
    @InjectView(R.id.textView2)
    TextView textView2;
    @InjectView(R.id.tv_gg_brand)
    TextView tvGgBrand;
    @InjectView(R.id.ll_gg_brand)
    LinearLayout llGgBrand;
    @InjectView(R.id.et_jt)
    EditText etJt;
    @InjectView(R.id.et_zj)
    EditText etZj;
    @InjectView(R.id.tv_bz)
    TextView tvBz;
    @InjectView(R.id.ll_bz)
    LinearLayout llBz;
    @InjectView(R.id.tv_jtai)
    TextView tvJtai;
    @InjectView(R.id.ll_jtai)
    LinearLayout llJtai;
    @InjectView(R.id.tv_date)
    TextView tvDate;
    @InjectView(R.id.ll_date)
    LinearLayout llDate;
    @InjectView(R.id.tv_inspector)
    TextView tvInspector;
    @InjectView(R.id.ll_inspector)
    LinearLayout llInspector;
    @InjectView(R.id.tv_b_weight)
    TextView tvBWeight;
    @InjectView(R.id.ll_b_weight)
    LinearLayout llBWeight;


    private WeakReference<Socket> mSocket;
    private ReadThread mReadThread;
    private Qcode mQcode;

    Observer<Result> observer = new Observer<Result>() {
        @Override
        public void onCompleted() {
            PLog.d("s", "onCompleted");
            hideWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            PLog.d("s", "" + e.getMessage());
            String errBody = ErrorHandler.handle(e);
            Snackbar.make(getActivity().getWindow().getDecorView(), "" + errBody, Snackbar.LENGTH_SHORT).show();
            hideWaitDialog();
        }

        @Override
        public void onNext(Result result) {
            hideWaitDialog();
            if (result.isSuccess()) {
                if (result.getStatusCode() == 200) {
                    Gson gson = new Gson();
                    Object objects = result.getData();
                    if (objects != null) {
                        String json = gson.toJson(objects);
//                        "title" : "护理佳纸业产品合格证",
//                                "cpdm" : "03.17.269",
//                                "cpmc" : "外卖原纸-无芯",
//                                "ggxh" : "15.5*466*3",
//                                "jietou" : "0",
//                                "zj" : "1100",
//                                "bz" :"乙班",
//                                "jt" : "三号分切机",
//                                "date" : date,
//                                "amount":"82.00",
//                                "username":"张三",
//                                "opendirection":"H:\\CLodopDemos\\arrow_right.png",
//                                "address":"河南省鹿邑县产业集聚区",
//                                "tax":"0394-7490258",
//                                "phone":"0394-7490998",
//                                "web":"WWW.hulijia.com",
//                                "qrcode":"1234567890版本7的最大值是122个字符123123",
//                                "code":"YZ99952017072818"
                        JSONObject jObject = new JSONObject();
                        try {
                            JSONObject jo = new JSONObject(json);
                            final String fBillNumber = jo.optString("FBillNumber");
                            final String fBase = jo.optString("FBase");
                            final String fBanzu = jo.optString("FBanzu");
                            final String FJiTai = jo.optString("FJiTai");
                            AppContext.getInstance().setProperty("fBanzu", fBanzu);
                            AppContext.getInstance().setProperty("fBanzuText", tvBz.getText().toString());
                            AppContext.getInstance().setProperty("FJiTai", FJiTai);
                            AppContext.getInstance().setProperty("FJiTaiText", tvJtai.getText().toString());
                            AppContext.getInstance().setProperty("baseId", fBase);
                            final String fWeight = jo.optString("FWeight");
                            //设置的ip打印地址
                            String set_ip = AppContext.getInstance().getProperty("set_ip");
                            if (!StringUtils.isEmpty(set_ip)) {
                                jObject.put("hostUrl", "http://" + set_ip + "/CLodopfuncs.js");
                                jObject.put("opendirection", "http://" + set_ip + "/images/arrow_right.png");
                            } else {
                                jObject.put("hostUrl", "http://192.168.0.170:8000/CLodopfuncs.js");
                                jObject.put("opendirection", "http://192.168.0.170:8000/images/arrow_right.png");
                            }
                            jObject.put("title", "护理佳产品合格证");
                            jObject.put("cpdm", tvGhUnit.getText().toString());
                            jObject.put("cpmc", tvCpName.getText().toString());
                            jObject.put("ggxh", tvGgBrand.getText().toString());
                            jObject.put("jietou", etJt.getText().toString());
                            jObject.put("zj", etZj.getText().toString());
                            jObject.put("bz", tvBz.getText().toString());
                            jObject.put("jt", tvJtai.getText().toString());
                            String nowYMDHMSTime1 = Time.getNowYMDHMSTime();
                            jObject.put("date", nowYMDHMSTime1);
                            tvDate.setText(nowYMDHMSTime1);
                            jObject.put("amount", fWeight);
//                            jObject.put("username", tvInspector.getText().toString());
                            jObject.put("address", "河南省鹿邑县产业集聚区");
                            jObject.put("tax", "0394-7490258");
                            jObject.put("phone", "0394-7490998");
                            jObject.put("web", "WWW.hulijia.com");
                            jObject.put("qrcode", json);
                            jObject.put("code", "" + fBillNumber);
                            String Fstring = jObject.toString();

                            Intent intent = new Intent();
                            Bundle bundle = new Bundle();
                            bundle.putString("fB", Fstring);
                            intent.putExtras(bundle);
                            UIHelper.showSimpleBack(mActivity, SimpleBackPage.WEB, bundle, "打印预览");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

//                mActivity.finish();
                    }
                }
            } else {
                Snackbar.make(mActivity.getWindow().getDecorView(), result.getMessage(), Snackbar.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = View.inflate(mActivity, R.layout.fragment_code, null);
        ButterKnife.inject(this, view);
        initView(view);
        initData();
        return view;
    }

    @Override
    public void initView(View view) {
        super.initView(view);
        setHasOptionsMenu(true);
        btnOk.setOnClickListener(this);
        llBWeight.setOnClickListener(this);
        llBz.setOnClickListener(this);
        llDate.setOnClickListener(this);
        llGhUnit.setOnClickListener(this);
        llJtai.setOnClickListener(this);
        final String ip = AppContext.getInstance().getProperty("rm_ip");
        String portstrString = AppContext.getInstance().getProperty("rm_port");

        if (!StringUtils.isEmpty(ip) && !StringUtils.isEmpty(portstrString)) {
            final int port = Integer.parseInt(portstrString);
            showWaitDialog();
            new Thread(new Runnable() {
                @Override
                public void run() {

                    startSocket(ip, port);
                }
            }).start();

        }
    }

    @Override
    public void initData() {
        super.initData();
        String nowYMDHMSTime = Time.getNowYMDHMSTime();
        tvDate.setText(nowYMDHMSTime);
        mQcode = new Qcode();
        mQcode.setFDate(nowYMDHMSTime);

        String baseId = AppContext.getInstance().getProperty("baseId");
        String fBanzu = AppContext.getInstance().getProperty("fBanzu");
        String fBanzuText = AppContext.getInstance().getProperty("fBanzuText");
        String FJiTai = AppContext.getInstance().getProperty("FJiTai");
        String FJiTaiText = AppContext.getInstance().getProperty("FJiTaiText");
        if (!StringUtils.isEmpty(fBanzu) && !StringUtils.isEmpty(fBanzuText)) {
            mQcode.setFBanZu(fBanzu);
            tvBz.setText(fBanzuText);
        }
        if (!StringUtils.isEmpty(FJiTai) && !StringUtils.isEmpty(FJiTaiText)) {
            mQcode.setFJiTai(FJiTai);
            tvJtai.setText(FJiTaiText);
        }

        if (!StringUtils.isEmpty(baseId)) {
            Add_Sync_Bean matById = AddSale_Manager.getInstance(mActivity).getMatById(baseId);

            String number = matById.getNumber();
            String name = matById.getName();
            String model = matById.getModel();
            tvGhUnit.setText(number);
            tvCpName.setText(name);
            tvGgBrand.setText(model + "");

            mQcode.setFBase(baseId);
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.send_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.send_btn:
                if (!StringUtils.isEmpty(etJt.getText().toString()) && !StringUtils.isEmpty(etZj.getText().toString())
                        && !StringUtils.isEmpty(etWeight.getText().toString()) && !StringUtils.isEmpty(tvGhUnit.getText().toString())
                        && !StringUtils.isEmpty(tvCpName.getText().toString())
                        ) {

                    String date = mQcode.getFDate();
                    String fClassTypeID = mQcode.getFClassTypeID();
                    String fBillNo = mQcode.getFBillNo();
                    String fBase = mQcode.getFBase();
                    String fBanZu = mQcode.getFBanZu();
                    String fJiTai = mQcode.getFJiTai();
                    String fEmp = mQcode.getFEmp();
                    String etWeights = etWeight.getText().toString();
                    String etJtou = etJt.getText().toString();
                    String etZjing = etZj.getText().toString();
                    String tv_b_weight = tvBWeight.getText().toString();

                    mQcode.setFDate(date);
                    mQcode.setFBase(fBase);
                    mQcode.setFEmp(fEmp);
                    mQcode.setFJiTai(fJiTai);
                    mQcode.setFBanZu(fBanZu);
                    mQcode.setFTouSum(etJtou);
                    mQcode.setFDiameter(etZjing);
                    if ("重 量".equals(etWeights) || "最后重量".equals(etWeights)) {
                        Snackbar.make(mActivity.getWindow().getDecorView(), "请确认正确重量值！", Snackbar.LENGTH_SHORT).show();
                        break;
                    } else if (!StringUtils.isEmpty(tv_b_weight)) {
                        mQcode.setFWeight("" + ((Integer.parseInt(etWeights)) - (Integer.parseInt(tv_b_weight))));
                    } else {
                        mQcode.setFWeight(etWeights);
                    }

                    showWaitDialog();
                    AddQcode_Bean addQcode_bean = new AddQcode_Bean();
                    addQcode_bean.setHeadDetail(mQcode);

                    Gson gson = new Gson();
                    String json = gson.toJson(addQcode_bean);
                    String token = AppContext.getInstance().getProperty(AppConfig.PRIVATE_TOKEN);
                    CM cm = new CM();
                    cm.setToken(token);
                    cm.setData(json);
                    RetrofitSingleton.getApiService(mActivity).
                            SubmitQcode(cm)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(observer);
                } else {
                    Snackbar.make(mActivity.getWindow().getDecorView(), "必填信息不能为空！", Snackbar.LENGTH_SHORT).show();
                }
                break;
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        Bundle bundle = new Bundle();
        switch (v.getId()) {
            case R.id.ll_b_weight:
                bundle.putString("type", "jbzl");
                UIHelper.showSimpleBackForResult(this, mActivity, 7, SimpleBackPage.CUST_PHEON, bundle, "胶棒重量");
                break;
            case R.id.btn_ok:
                String weight = tvWeight.getText().toString();
                if (weight != null) {
                    etWeight.setText(weight);
                }
                break;
            case R.id.ll_gh_unit:
                bundle.putString("type", "cpdm");
                UIHelper.showSimpleBackForResult(this, mActivity, 1, SimpleBackPage.CUST_PHEON, bundle, "产品代码");
//                List<Add_Sync_Bean> addSyncBean = AddSale_Manager.getInstance(mActivity).getAddSyncBean();
                break;
            case R.id.ll_cp_name:
                bundle.putString("type", "cpmc");
                UIHelper.showSimpleBackForResult(this, mActivity, 2, SimpleBackPage.CUST_PHEON, bundle, "产品名称");

                break;
            case R.id.ll_gg_brand:
                bundle.putString("type", "ggxh");
                UIHelper.showSimpleBackForResult(this, mActivity, 3, SimpleBackPage.CUST_PHEON, bundle, "规格型号");

                break;
            case R.id.ll_bz:
                bundle.putString("type", "bz");
                UIHelper.showSimpleBackForResult(this, mActivity, 4, SimpleBackPage.CUST_PHEON, bundle, "班组");

                break;
            case R.id.ll_jtai:
                bundle.putString("type", "jtai");
                UIHelper.showSimpleBackForResult(this, mActivity, 5, SimpleBackPage.CUST_PHEON, bundle, "机台");

                break;
            case R.id.ll_date:
                new SlideDateTimePicker.Builder(getFragmentManager())
                        .setListener(listener)
                        .setInitialDate(new Date())
                        .build()
                        .show();

                break;
            case R.id.ll_inspector:
                bundle.putString("type", "jyy");
                UIHelper.showSimpleBackForResult(this, mActivity, 6, SimpleBackPage.CUST_PHEON, bundle, "检验员");

                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            final CustPhone item = (CustPhone) data.getSerializableExtra("item");
            if (item != null) {
                String name = item.getName();
                String id = item.getId();
                switch (requestCode) {
                    case 1:
                        String number = item.getNumber();
                        tvGhUnit.setText(number + "");
                        mQcode.setFBase(id);
//                        addSaleInt_HeadBean.setFDeptName(name);
//                        break;
                    case 2:
                        Add_Sync_Bean matById = AddSale_Manager.getInstance(mActivity).getMatById(id);
                        if (matById == null) {
                            Snackbar.make(mActivity.getWindow().getDecorView(), "请先同步数据！", Snackbar.LENGTH_SHORT).show();
                            break;
                        } else {
                            String name1 = matById.getName();
                            tvCpName.setText(name1 + "");
                        }
//                        mQcode.setFBase(id);
//                        addSaleInt_HeadBean.setFUserName(name);
//                        break;
                    case 3:
                        Add_Sync_Bean matById1 = AddSale_Manager.getInstance(mActivity).getMatById(id);
                        String model = matById1.getModel();
                        tvGgBrand.setText(model + "");
//                        mQcode.setFBase(id);
//                        addSaleInt_HeadBean.setFBUserName(name);
                        break;
                    case 4:
                        tvBz.setText(name);
                        mQcode.setFBanZu(id);
//                        addSaleInt_HeadBean.setFYUserName(name);
                        break;
                    case 5:
                        tvJtai.setText(name);
                        mQcode.setFJiTai(id);
//                        addSaleInt_HeadBean.setFStockName(name);
                        break;
                    case 6:
                        tvInspector.setText(name);
                        mQcode.setFEmp(id);
//                        addSaleInt_HeadBean.setFStockName(name);
                        break;
                    case 7:
                        tvBWeight.setText("" + name);
//                        addSaleInt_HeadBean.setFStockName(name);
                        break;
                }
            }
        }
    }

    private SlideDateTimeListener listener = new SlideDateTimeListener() {

        @Override
        public void onDateTimeSet(Date date) {
            String str = StringUtils.getDateString(date);
            tvDate.setText(str);
            mQcode.setFDate(str);
        }

        @Override
        public void onDateTimeCancel() {
        }
    };

    private void startSocket(String ip, int port) {
        try {
            Socket so = new Socket();
            SocketAddress socAddress = new InetSocketAddress(ip, port);
            so.connect(socAddress, 3000);
            mSocket = new WeakReference<Socket>(so);
            mReadThread = new ReadThread(so);
            mReadThread.start();
        } catch (IOException e) {
            e.printStackTrace();
            hideWaitDialog();
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    expView_container.setVisibility(View.VISIBLE);
                }
            });
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    // Thread to read content from Socket
    class ReadThread extends Thread {
        private WeakReference<Socket> mWeakSocket;
        private boolean isStart = true;

        public ReadThread(Socket socket) {
            hideWaitDialog();
            mWeakSocket = new WeakReference<Socket>(socket);
        }

        public void release() {
            isStart = false;
            releaseLastSocket(mWeakSocket);
        }

        @Override
        public void run() {
            super.run();
            Socket socket = mWeakSocket.get();
            if (null != socket) {
                try {
                    socket.setKeepAlive(true);
                    InputStream is = socket.getInputStream();
                    byte[] buffer = new byte[1024 * 4];
                    int length = 0;
                    while (!socket.isClosed() && !socket.isInputShutdown()
                            && isStart && ((length = is.read(buffer)) != -1)) {
                        if (length > 0) {
                            String message = StringUtils.bytes2HexString(buffer, length);
                            Message msg = new Message();
                            Bundle bundle = new Bundle();
                            bundle.clear();
                            msg.what = 0;
                            bundle.putString("msg", message);
                            msg.setData(bundle);
                            // 发送消息 修改UI线程中的组件
                            myHandler.sendMessage(msg);
                        }
                    }
                } catch (IOException e) {
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            expView_container.setVisibility(View.VISIBLE);
                        }
                    });
                    mReadThread.release();
                    releaseLastSocket(mSocket);
//                    new InitSocketThread().start();
                }
            } else {
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        expView_container.setVisibility(View.VISIBLE);
                    }
                });
            }
        }
    }

    public Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                Bundle bundle = msg.getData();
                String str = bundle.getString("msg");

//                String substring = str.substring(0, 24);
//                PLog.d("zh", substring + "--=-=-=");
                pas(str);
            }
        }
    };

    /**
     * 解析字符串
     *
     * @param str
     */
    private void pas(String str) {
        byte[] rcvBuf = StringUtils.convert2HexArray(str);
        if (rcvBuf.length == 12) {
            String headStr = str.substring(0, 2);
            String endStr = str.substring(str.length() - 2, str.length());

            if ("02".equals(headStr) && "03".equals(endStr)) {
                String num = str.substring(2, 16);

                int anInt = Integer.parseInt(toStringHex1(num)); //-12
                if (tvWeight != null) {
                    tvWeight.setText("" + anInt);
                } else {
                }
            } else {
                Snackbar.make(mActivity.getWindow().getDecorView(), "格式不正确！", Snackbar.LENGTH_SHORT).show();
            }
        } else {
            Snackbar.make(mActivity.getWindow().getDecorView(), "长度不正确！", Snackbar.LENGTH_SHORT).show();
        }
    }

    /**
     * 十六进制转asicc
     *
     * @param s
     * @return
     */
    public static String toStringHex1(String s) {
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(
                        i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "ASCII");
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    private void releaseLastSocket(WeakReference<Socket> mSocket) {
        try {
            if (mSocket != null) {
                Socket sk = mSocket.get();
                if (!sk.isClosed()) {
                    sk.close();
                }
                sk = null;
                mSocket = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onBackPressed() {
        try {
            if (mSocket != null) {
                Socket sk = mSocket.get();
                if (sk != null) {
                    if (!sk.isClosed()) {
                        sk.close();
                    }
                    sk = null;
                    mSocket = null;
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return super.onBackPressed();
    }
}
